package com.basic.business.shift.service.impl;

import com.basic.common.constant.CacheConstants;
import com.basic.common.core.redis.RedisCacheUtils;
import org.springframework.stereotype.Service;
import com.basic.common.core.service.impl.BaseServiceImpl;
import com.basic.business.shift.domain.TShiftMgmt;
import com.basic.business.shift.service.ITShiftMgmtService;
import com.basic.business.shift.mapper.TShiftMgmtMapper;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalTime;
import java.util.List;

/**
 * 业务-班次管理Service业务层处理
 *
 * @author zhaoxy_jn@163.com
 */
@Service
public class TShiftMgmtServiceImpl extends BaseServiceImpl<TShiftMgmtMapper,TShiftMgmt> implements ITShiftMgmtService {

    @Resource
    private TShiftMgmtMapper tShiftMgmtMapper;

    /**
     * 项目启动时，初始化班次信息缓存
     */
    @PostConstruct
    public void init(){
        resetShiftCache();
    }

    @Override
    public List<TShiftMgmt> getNormalShiftInfo() {
        return tShiftMgmtMapper.getNormalShiftInfo();
    }

    @Override
    public void resetShiftCache() {
        // 清空缓存
        RedisCacheUtils.clearCache(CacheConstants.SHIFT_REDIS_KEY + "*");
        // 加载缓存
        loadingShiftCache();
    }

    /**
     * 加载班次信息缓存
     */
    private void loadingShiftCache() {
        RedisCacheUtils.setCacheObject(CacheConstants.SHIFT_REDIS_KEY, getNormalShiftInfo());
    }

    @Override
    public int updateStatusByIds(String[] ids, String status) {
        return tShiftMgmtMapper.updateStatusByIds(ids, status);
    }

    @Override
    public int insert(TShiftMgmt po) {
        checkTimeRangeOverlap(po);
        return super.insert(po);
    }

    @Override
    public int update(TShiftMgmt po) {
        checkTimeRangeOverlap(po);
        return super.update(po);
    }

    /**
     * 检查时间范围是否与其他班次存在交叉
     */
    private void checkTimeRangeOverlap(TShiftMgmt po){
        // 获取新班次的开始时间和结束时间
        LocalTime newStartTime = po.getStartTime();
        LocalTime newEndTime = po.getEndTime();

        // 查询所有班次信息
        List<TShiftMgmt> shiftList = tShiftMgmtMapper.getList(new TShiftMgmt());

        // 检查时间范围是否交叉
        boolean isOverlap = shiftList.stream().filter(shift -> !shift.getId().equals(po.getId())).anyMatch(existingShift -> {
            LocalTime existingStartTime = existingShift.getStartTime();
            LocalTime existingEndTime = existingShift.getEndTime();

            // 检查时间范围是否重叠
            return (newStartTime.isBefore(existingEndTime) && newEndTime.isAfter(existingStartTime)) ||
                    (newStartTime.equals(existingStartTime) && newEndTime.equals(existingEndTime));
        });

        if (isOverlap) {
            throw new RuntimeException("时间范围与其他班次存在交叉，请重新添加");
        }
    }
}
